"""
图形化页面
"""
import json
import os
import tkinter as tk
from tkinter import *
from tkinter import ttk
# from core.src_thread import NEW_WORKBOOK
from conf.settings import JSON_FILE, WORKBOOK
from core import src_thread
from core.src_thread import logger
from interface.init_interface import config_dict
from interface.init_interface import init_settings

# 初始化配制文件
if not config_dict:
    init_settings()
    print(config_dict.get('WEB').get('ALL_URL'))

# 初始化窗体
app = Tk()
app.title("HostAutomation v1.2.1")
app.geometry('600x600+500+200')
app.iconbitmap("./conf/favicon.ico")

# 页面布局
# 行距
space = 80
# 模式列表
mode_list = ['模式1 测试连接+账号查询+手工同步', '模式2 只测试连接',
             '模式3 只初始化', '模式4 只手工同步']
# 允许初始化的主机状态列表
init_status_list = ['1 未初始化 初始化失败', '2 未初始化']
# 线程列表
thread_list = list(range(1, os.cpu_count()))


# 开始运行
def click_start_button():
    src_thread.run()
    from core.src_thread import NEW_WORKBOOK
    os.startfile(NEW_WORKBOOK)


start_button = tk.Button(app, text='开始运行', command=click_start_button, font=('黑体', 12),
                         activebackground='#7CCD7C', bg='#C1CDCD')
start_button.place(x=130, y=40, width=100, height=40)


def click_open_button():
    os.startfile(WORKBOOK)


open_button = tk.Button(app, text='打开模板', command=click_open_button, font=('黑体', 12), activebackground='#7CCD7C',
                        bg='#E8E8E8')
open_button.place(x=330, y=40, width=100, height=40)


# 打开上次运行结果
def click_result_button():
    from core.src_thread import NEW_WORKBOOK
    os.startfile(NEW_WORKBOOK)


result_button = tk.Button(app, text='打开运行结果', command=click_result_button, font=('黑体', 12),
                          activebackground='#7CCD7C', bg='#E8E8E8')
result_button.place(x=120, y=40 + space, width=130, height=40)


# 打开结果文件夹
def click_result_directory_button():
    from core.src_thread import NEW_WORKBOOK
    os.startfile(os.path.dirname(NEW_WORKBOOK))


result_directory_button = tk.Button(app, text='打开结果文件夹', command=click_result_directory_button,
                                    font=('黑体', 12), activebackground='#7CCD7C',
                                    bg='#E8E8E8')
result_directory_button.place(x=300, y=40 + space, width=150, height=40)

# 模式
mode_label = tk.Label(app, text='模式:', font=('黑体', 12))
mode_label.place(x=60, y=40 + space * 2)
mode_combobox = ttk.Combobox(app)
mode_combobox.place(x=170, y=40 + space * 2, width=300, height=30)
mode_combobox['value'] = mode_list
mode_combobox.current(config_dict.get('MODE') - 1)


def mode_combobox_bind(event):
    print(mode_combobox.current() + 1)
    config_dict["MODE"] = mode_combobox.current() + 1
    config_save(config_dict)


mode_combobox.bind("<<ComboboxSelected>>", mode_combobox_bind)

# 线程数量
thread_label = tk.Label(app, text='线程数量:', font=('黑体', 12))
thread_label.place(x=60, y=40 + space * 3)
thread_combobox = ttk.Combobox(app)
thread_combobox.place(x=170, y=40 + space * 3, width=200, height=30)
thread_combobox['value'] = thread_list
thread_combobox.current(config_dict.get('MAX_THREAD') - 1)


def thread_combobox_bind(event):
    print(thread_combobox.current() + 1)
    config_dict["MAX_THREAD"] = thread_combobox.current() + 1
    config_save(config_dict)


thread_combobox.bind("<<ComboboxSelected>>", thread_combobox_bind)

# 允许初始化的主机（模式3生效）
init_label = tk.Label(app, text='允许初始化的主机:\n（模式3生效）', font=('黑体', 12))
init_label.place(x=60, y=40 + space * 4)
init_combobox = ttk.Combobox(app)
init_combobox.place(x=200, y=40 + space * 4, width=200, height=30)
init_combobox['value'] = init_status_list
init_combobox.current(config_dict.get('ALLOWS_INIT_STATUS') - 1)


def init_combobox_bind(event):
    print(init_combobox.current() + 1)
    config_dict["ALLOWS_INIT_STATUS"] = init_combobox.current() + 1
    config_save(config_dict)


init_combobox.bind("<<ComboboxSelected>>", init_combobox_bind)

# 地址选择
URL_label = tk.Label(app, text='管理平台地址:', font=('黑体', 12))
URL_label.place(x=60, y=40 + space * 5)
URL_combobox = ttk.Combobox(app)
URL_combobox.place(x=170, y=40 + space * 5, width=200, height=30)
url_list = list(config_dict.get('WEB').get('ALL_URL'))
URL_combobox['value'] = url_list
open_url = config_dict.get('WEB').get('OPEN_URL')
URL_combobox.current(url_list.index(open_url))


def URL_combobox_bind(event):
    print(type(URL_combobox.get()), URL_combobox.get())
    config_dict["WEB"]["OPEN_URL"] = URL_combobox.get()
    print(config_dict)
    config_save(config_dict)


URL_combobox.bind("<<ComboboxSelected>>", URL_combobox_bind)


# 地址配置（配置后需要重启）
def click_config_button():
    os.startfile(JSON_FILE)


config_button = tk.Button(app, text='配置地址\n(重启生效)', command=click_config_button, font=('黑体', 12),
                          activebackground='#7CCD7C', bg='#E8E8E8')
config_button.place(x=430, y=30 + space * 5, width=100, height=50)

# 账号密码


user_label = tk.Label(app, text='用户名:', font=('黑体', 12))
user_label.place(x=60, y=40 + space * 6)
user_str = tk.StringVar()
user_str.set(config_dict.get('WEB').get('USER'))
user_entry = tk.Entry(app, textvariable=user_str)
user_entry.place(x=120, y=40 + space * 6)

passwd_label = tk.Label(app, text='密码:', font=('黑体', 12))
passwd_label.place(x=300, y=40 + space * 6)
passwd_str = tk.StringVar()
passwd_str.set(config_dict.get('WEB').get('PASSWORD'))
passwd_entry = tk.Entry(app, textvariable=passwd_str)
passwd_entry.place(x=360, y=40 + space * 6)


def user_info_save(event):
    print(user_entry.get(), '  ', passwd_entry.get())
    config_dict["WEB"]["USER"] = user_entry.get()
    config_dict["WEB"]["PASSWORD"] = passwd_entry.get()
    config_save(config_dict)


user_entry.bind("<FocusOut>", user_info_save)
passwd_entry.bind("<FocusOut>", user_info_save)


def config_save(json_dict):
    with open('./conf/settings.json', 'w') as f:
        json.dump(json_dict, f)


# 主循环
app.mainloop()
